package com.jmebananas.image.util;

import java.nio.ByteBuffer;

import com.jme.image.Image;
import com.jme.renderer.ColorRGBA;

/**
 * ImageUtil
 * 
 * @author Glenn Powell
 * 
 */
public class ImageUtil {

	public static ColorRGBA getColorRGBA(Image image, int x, int y, ColorRGBA color) {
		if (color == null)
			color = new ColorRGBA(0, 0, 0, 1);

		if (x >= 0 && x < image.getWidth() && y >= 0 && y < image.getHeight()) {
			ByteBuffer buffer = image.getData();
			int pixel = y * image.getWidth() + x;
			int index = 0;
			
			switch (image.getType()) {
			case Image.RA88:
				index = pixel * 2;
				color.r = (buffer.get(index) & 0xff) / 255f;
				color.a = (buffer.get(index + 1) & 0xff) / 255f;
				break;
			case Image.RGB888:
				index = pixel * 3;
				color.r = (buffer.get(index) & 0xff) / 255f;
				color.g = (buffer.get(index + 1) & 0xff) / 255f;
				color.b = (buffer.get(index + 2) & 0xff) / 255f;
				break;
			case Image.RGBA4444:
				index = pixel * 2;
				color.r = ((buffer.get(index) >> 4)) / 15f;
				color.g = ((buffer.get(index) & 0xf)) / 15f;
				color.b = ((buffer.get(index + 1) >> 4)) / 15f;
				color.a = ((buffer.get(index + 1) & 0xf)) / 15f;
				break;
			case Image.RGBA8888:
				index = pixel * 4;
				color.r = (buffer.getChar(index) & 0xff) / 255f;
				color.g = (buffer.getChar(index + 1) & 0xff) / 255f;
				color.b = (buffer.getChar(index + 2) & 0xff) / 255f;
				color.a = (buffer.getChar(index + 3) & 0xff) / 255f;
				break;
			}
		}
		return color;
	}

	public static float getAlpha(Image image, int x, int y) {
		if (x < 0 || x >= image.getWidth() || y < 0 || y >= image.getHeight())
			return 0.0f;
		
		ByteBuffer buffer = image.getData();
		int pixel = y * image.getWidth() + x;
		int index = 0;

		switch (image.getType()) {
		case Image.RA88:
			index = pixel * 2;
			return (buffer.get(index + 1) & 0xff) / 255f;
		case Image.RGBA4444:
			index = pixel * 2;
			return ((buffer.get(index + 1) & 0xf)) / 15f;
		case Image.RGBA8888:
			index = pixel * 4;
			return (buffer.get(index + 3) & 0xff) / 255f;
		}
		return 1.0f;
	}

}
